package com.small.springframework.beans.factory.support;


import com.small.springframework.beans.BeansException;
import com.small.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory{

    InstantiationStrategy instantiation = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition,Object[] args) throws BeansException {
        Object bean = null;
        try {
            bean = createInstanceBean(beanName,beanDefinition,args);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        addSingleton(beanName, bean);
        return bean;
    }


    private Object createInstanceBean(String beanName, BeanDefinition beanDefinition,Object[] args) {

        Class beanClass = beanDefinition.getBeanClass();
        Constructor[] declaredConstructors = beanClass.getDeclaredConstructors();
        Constructor constructor = null;
        for (Constructor ctr:declaredConstructors) {
            if (args != null && args.length == ctr.getParameterTypes().length){
                constructor = ctr;
                break;
            }
        }

        return getInstantiation().instantiate(beanDefinition,beanName,constructor,args);
    }

    private InstantiationStrategy getInstantiation() {
        return instantiation;
    }

}
